/*
 * Copyright (C) Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.light.server.persistence.dao;

import static com.google.light.server.utils.LightPreconditions.checkPersonId;
import static com.google.light.server.utils.ObjectifyUtils.assertAndReturnUniqueEntity;

import java.util.logging.Logger;

import com.google.inject.Inject;
import com.google.light.server.dto.person.PersonDto;
import com.google.light.server.dto.pojo.typewrapper.longwrapper.PersonId;
import com.google.light.server.exception.unchecked.EmailInUseException;
import com.google.light.server.persistence.entity.person.PersonEntity;
import com.google.light.server.utils.ObjectifyUtils;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

/**
 * DAO for {@link PersonEntity}.
 * 
 * @author Arjun Satyapal
 */
public class PersonDao extends AbstractBasicDao<PersonDto, PersonEntity> {
  private static final Logger logger = Logger.getLogger(PersonDao.class.getName());

  static {
    ObjectifyService.register(PersonEntity.class);
  }

  @Inject
  public PersonDao() {
    super(PersonEntity.class);
  }

  /**
   * Fetch PersonEntity by Email. The underlying assumption is that only one Person Exists with an
   * email. If no PersonEntity is found, then returns null.
   * 
   * @param email
   * @return
   */
  public PersonEntity findByEmail(String email) {
    Objectify ofy = ObjectifyUtils.nonTransaction();

    Query<PersonEntity> query =
        ofy.query(PersonEntity.class).filter(PersonEntity.OFY_EMAIL_QUERY_STRING, email);

    String errMessage = "For email=[" + email + "], found more then 1 record.";
    return assertAndReturnUniqueEntity(query, errMessage);
  }

  /**
   * Put Person on datastore. Id for {@link PersonEntity} is generated by DataStore.
   * 
   * {@inheritDoc}
   */
  @Override
  public PersonEntity put(Objectify txn, PersonEntity entity) {
    PersonEntity existingEntity = this.findByEmail(entity.getEmail());
    if (existingEntity != null) {
      /*
       * There is already an entity with given email, and a new entity is attempted to be persisted
       * with same emailId.
       */
      if (!existingEntity.getPersonId().equals(entity.getPersonId()))
        throw new EmailInUseException();
    }
    boolean isCreate = false;
    if (entity.getPersonId() == null) {
      isCreate = false;
    }

    PersonEntity returnEntity = super.put(txn, entity);
    String returnMsg = "";

    if (isCreate) {
      returnMsg = "Created PersonEntity[" + returnEntity.getPersonId() + "].";
    } else {
      returnMsg = "Updated PersonEntity[" + returnEntity.getPersonId() + "].";
    }

    return logAndReturn(logger, returnEntity, returnMsg);
  }

  /**
   * TODO(arjuns): Add test for this.
   * Fetch Person via PersonId.
   */
  public PersonEntity get(PersonId personId) {
    checkPersonId(personId);
    return super.get(PersonEntity.generateKey(personId));
  }

}
